package com.ruoyi.electronicFence.service.Impl;

import com.ruoyi.electricity.domain.vo.AlarmsHandleCountForEachHourOfTheDay;
import com.ruoyi.electronicFence.domain.*;
import com.ruoyi.electronicFence.domain.TEfAlarmVO;
import com.ruoyi.electronicFence.domain.TEfEquipmentDeviceVo;
import com.ruoyi.electronicFence.mapper.*;
import com.ruoyi.electronicFence.service.EFAnalysisService;
import com.ruoyi.electronicFence.service.ITEfEquipmentDeviceService;
import com.ruoyi.electronicFence.service.ITEfFenceAreaService;
import com.ruoyi.rsikManage.domain.AlarmEvent;
import com.ruoyi.rsikManage.domain.AlarmEventRequest;
import com.ruoyi.rsikManage.mapper.MonitorPointMapper;
import com.ruoyi.rsikManage.service.StatisticalAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class EFAnalysisServiceImpl implements EFAnalysisService {

    @Autowired
    StatisticalAnalysisService statisticalAnalysisService;
    @Autowired
    private ITEfFenceAreaService tEfFenceAreaService;
    @Autowired
    private EFAnalysisMapper eFAnalysisMapper;
    @Autowired
    private MonitorPointMapper monitorPointMapper;
    @Autowired
    private TEfAlarmMapper tEfAlarmMapper;
    @Autowired
    private TDeviceStatusMapper tDeviceStatusMapper;
    @Autowired
    private TEfFenceAreaMapper tEfFenceAreaMapper;

    @Autowired
    private TEfEquipmentDeviceMapper tEfEquipmentDeviceMapper;

    @Autowired
    private ITEfEquipmentDeviceService tEfEquipmentDeviceService;
    @Override
    public Map<String, Object> selectIndexInfo(EFAnalysisRequest eFAnalysisRequest) {
        HashMap<String, Object> map = new HashMap<>();
        LocalDateTime defaultStartDateTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 指定日期时间格式
        String DEFAULT_START_TIME = defaultStartDateTime.format(formatter); // 格式化日期时间为字符串

        AlarmEventRequest alarmEventRequest = new AlarmEventRequest();
        alarmEventRequest.setPageNum(1);
        alarmEventRequest.setPageSize(Integer.MAX_VALUE);
        alarmEventRequest.setStartTime(eFAnalysisRequest.getStartDate() != null ? eFAnalysisRequest.getStartDate() : DEFAULT_START_TIME);
        alarmEventRequest.setEndTime(eFAnalysisRequest.getEndDate() != null ? eFAnalysisRequest.getEndDate() : null);
        List<AlarmEvent> alarmEvents = statisticalAnalysisService.selectAllAlarmInfoEF(alarmEventRequest);
        //List<AlarmEvent> alarmEvents 遍历该列表 计算出 不同areaId 下 的个数 以及  不同 alarm_level 的个数
        // Map 用于记录不同 areaId 下的个数和不同 alarm_level 的个数
        Map<String, Long> alarmLevelCounts = new HashMap<>();

        // 输出不同 alarmLevel 依次等于 1、2、3、4、5 的个数
        for (int i = 1; i <= 5; i++) {
            // 将整数转换为字符串
            String alarmLevel = String.valueOf(i);
            // 使用流进行筛选和计数
            long count = alarmEvents.stream()
                    .filter(alarmEvent -> alarmEvent.getAlarmLevel().equals(alarmLevel))
                    .count();
            // 将计数结果放入到 alarmLevelCounts 中
            alarmLevelCounts.put(String.valueOf(6-i), count);
        }

        map.put("alarmLevelCounts",alarmLevelCounts);
        ArrayList<Object> areaList = new ArrayList<>();
        Map<String, Long> totalStatusCounts = new HashMap<>();
        // 查询区域 以及相关报警信息 处置信息
        List<TEfFenceArea> Areas = tEfFenceAreaService.selectTEfFenceAreaDetailsList(new TEfFenceArea());
        for (TEfFenceArea area : Areas) {
            List<TEfAreaApe> tEfAreaApes = area.getTEfAreaApes();
            List<String> apeIds = tEfAreaApes.stream().map(TEfAreaApe::getApeId).collect(Collectors.toList());

            // 统计该 area 下的事件
            long alarmCount = alarmEvents.stream().filter(event -> apeIds.contains(event.getDeviceId())).count();

            // 统计各个状态的数量
            Map<String, Long> countByHandelStatus = alarmEvents.stream()
                    .filter(event -> apeIds.contains(event.getDeviceId()))
                    .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus, Collectors.counting()));

            // 更新总的状态数量统计
            countByHandelStatus.forEach((status, count) -> totalStatusCounts.merge(status, count, Long::sum));

            // 构建 areaMap
            Map<String, Object> areaMap = new HashMap<>();
            areaMap.put("areaId", area.getId());
            areaMap.put("areaName", area.getAreaName());
            areaMap.put("alarmCount", alarmCount);
            areaMap.put("handelStatus1", countByHandelStatus.getOrDefault("1", 0L));
            areaMap.put("handelStatus2", countByHandelStatus.getOrDefault("2", 0L));
            areaMap.put("handelStatus3", countByHandelStatus.getOrDefault("3", 0L));

            areaList.add(areaMap);
        }
        ArrayList<Map<String, Object>> totalStatusList = new ArrayList<>();
        // 在循环结束后，添加总的状态统计信息
        totalStatusCounts.forEach((status, count) -> {
            Map<String, Object> statusMap = new HashMap<>();
            statusMap.put("status", status);
            statusMap.put("count", count);
            totalStatusList.add(statusMap);
        });


        //List<AlarmEvent> alarmEvents 遍历该列表 按小时对 handleTime分组然后统计其组内对 handelStatus 为3的个数 存入map中 例如 "01:00:00",2  "01:00:00",4
        Map<String, Long> handleStatusCountsByHour = new HashMap<>();
        //List<TEfFenceArea> Areas
        // 创建一个 Set 来存储所有的 apeId
        Set<String> apeIdSet = new HashSet<>();
        // 遍历 Areas 中的 TEfFenceArea 对象
        for (TEfFenceArea area : Areas) {
            // 获取 TEfFenceArea 对象中的 TEfAreaApe 列表
            List<TEfAreaApe> apes = area.getTEfAreaApes();
            // 遍历 TEfAreaApe 列表，提取并去重 apeId
            for (TEfAreaApe ape : apes) {
                apeIdSet.add(ape.getApeId());
            }
        }

        // 将 Set 转换为 List
        List<String> uniqueApeIds = new ArrayList<>(apeIdSet);
        List<AlarmsHandleCountForEachHourOfTheDay> HandleCountByHour = eFAnalysisMapper.countEFAlarmsForEachHourOfTheDay(uniqueApeIds);

        for (AlarmEvent alarmEvent:alarmEvents){
            Date handleTime = alarmEvent.getHandleTime();
            String handleStatus = alarmEvent.getHandelStatus();
        }
        Map<String, Object> CountByType = new HashMap<>();
        Map<String, Object> CountByType2 = new HashMap<>();
        Map<String, Object> CountByType3 = new HashMap<>();

        ArrayList<Map<String, Object>> CountByTypeList = new ArrayList<>();
        CountByType.put("name","AI摄像机报警");
        CountByType.put("count",15);
        CountByType.put("isHandle",6);

        CountByType2.put("name","红外热成像报警");
        CountByType2.put("count",20);
        CountByType2.put("isHandle",5);

        CountByType3.put("name","精准定位报警");
        CountByType3.put("count",15);
        CountByType3.put("isHandle",4);

        CountByTypeList.add(CountByType);
        CountByTypeList.add(CountByType2);
        CountByTypeList.add(CountByType3);
        HashMap<String, Integer> ArmedMonitorMap = monitorPointMapper.selectTotalMonitorCountAndOnlineMonitorCountForUnitCodes(uniqueApeIds,null);
        HashMap<String, Integer> MonitorMap = monitorPointMapper.selectTotalMonitorCountAndOnlineMonitorCount();
        HashMap<String, Object> ArmedMonitor = new HashMap<>();
        HashMap<String, Object> Monitor = new HashMap<>();

        ArmedMonitor.put("totalMonitorCount", ArmedMonitorMap.get("totalMonitorCount"));
        ArmedMonitor.put("onlineMonitorCount", ArmedMonitorMap.get("onlineMonitorCount"));

        Monitor.put("totalMonitorCount", MonitorMap.get("totalMonitorCount"));
        Monitor.put("onlineMonitorCount", MonitorMap.get("onlineMonitorCount"));
        //List<AlarmEvent> alarmEvents 统计个数 以及 handelStatus3 的个数 存入 countMap中
        long totalCount = alarmEvents.size(); // 获取总数量
        HashMap<String, Object> AlarmCount = new HashMap<>();
        // 使用流来计数符合条件的事件
        long isHandel = alarmEvents.stream()
                .filter(event -> event.getHandelStatus().equals("3"))
                .count();
        AlarmCount.put("totalCount",totalCount);
        AlarmCount.put("isHandel",isHandel);

        map.put("HandleCountByHour",HandleCountByHour);
        map.put("areaList",areaList);
        map.put("CountByTypeList",CountByTypeList);
        map.put("ArmedMonitor",ArmedMonitor);
        map.put("Monitor",Monitor);
        map.put("AlarmCount",AlarmCount);
        return map;
    }


    @Override
    public String selectIndexInfo2(EFAnalysisRequest eFAnalysisRequest) {
        String str;
        str="{\n" +
                "    \"data\": {\n" +
                "        \"alarmLevelCounts\": {\n" +
                "            \"1\": 0,\n" +
                "            \"2\": 0,\n" +
                "            \"3\": 0,\n" +
                "            \"4\": 0,\n" +
                "            \"5\": 0\n" +
                "        },\n" +
                "        \"CountByTypeList\": [\n" +
                "            {\n" +
                "                \"name\": \"AI摄像机报警\",\n" +
                "                \"count\": 15,\n" +
                "                \"isHandle\": 6\n" +
                "            },\n" +
                "            {\n" +
                "                \"name\": \"红外热成像报警\",\n" +
                "                \"count\": 20,\n" +
                "                \"isHandle\": 5\n" +
                "            },\n" +
                "            {\n" +
                "                \"name\": \"精准定位报警\",\n" +
                "                \"count\": 15,\n" +
                "                \"isHandle\": 4\n" +
                "            }\n" +
                "        ],\n" +
                "        \"Monitor\": {\n" +
                "            \"totalMonitorCount\": 384,\n" +
                "            \"onlineMonitorCount\": 175\n" +
                "        },\n" +
                "        \"areaList\": [\n" +
                "            {\n" +
                "                \"alarmCount\": 25,\n" +
                "                \"areaId\": 1,\n" +
                "                \"areaName\": \"掘进设备危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 9\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 4,\n" +
                "                \"areaId\": 2,\n" +
                "                \"areaName\": \"错护装备危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 2\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 5,\n" +
                "                \"areaId\": 3,\n" +
                "                \"areaName\": \"辅助作业装备危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 3\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 30,\n" +
                "                \"areaId\": 4,\n" +
                "                \"areaName\": \"破碎机、连运头车危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 5\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 15,\n" +
                "                \"areaId\": 5,\n" +
                "                \"areaName\": \"运输危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 7\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 20,\n" +
                "                \"areaId\": 6,\n" +
                "                \"areaName\": \"溜煤眼煤仓危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 02\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 23,\n" +
                "                \"areaId\": 7,\n" +
                "                \"areaName\": \"密闭墙危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 5\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 23,\n" +
                "                \"areaId\": 7,\n" +
                "                \"areaName\": \"运输车头危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 5\n" +
                "            },\n" +        "            {\n" +
                "                \"alarmCount\": 29,\n" +
                "                \"areaId\": 7,\n" +
                "                \"areaName\": \"井底车场危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 5\n" +
                "            },\n" +
                "            {\n" +
                "                \"alarmCount\": 4,\n" +
                "                \"areaId\": 9,\n" +
                "                \"areaName\": \"转载机危险区域\",\n" +
                "                \"handelStatus2\": 0,\n" +
                "                \"handelStatus3\": 0,\n" +
                "                \"handelStatus1\": 0\n" +
                "            }\n" +
                "        ],\n" +
                "        \"HandleCountByHour\": [\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 0,\n" +
                "                \"total\": 2,\n" +
                "                \"unhandled\": 1,\n" +
                "                \"handled\": 1\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 1,\n" +
                "                \"total\": 4,\n" +
                "                \"unhandled\": 2,\n" +
                "                \"handled\": 2\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 2,\n" +
                "                \"total\": 4,\n" +
                "                \"unhandled\": 2,\n" +
                "                \"handled\": 2\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 3,\n" +
                "                \"total\": 3,\n" +
                "                \"unhandled\": 3,\n" +
                "                \"handled\": 0\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 4,\n" +
                "                \"total\": 10,\n" +
                "                \"unhandled\": 0,\n" +
                "                \"handled\": 10\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 5,\n" +
                "                \"total\": 20,\n" +
                "                \"unhandled\": 14,\n" +
                "                \"handled\": 6\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 6,\n" +
                "                \"total\": 15,\n" +
                "                \"unhandled\": 5,\n" +
                "                \"handled\": 10\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 7,\n" +
                "                \"total\": 12,\n" +
                "                \"unhandled\": 6,\n" +
                "                \"handled\": 6\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 8,\n" +
                "                \"total\": 15,\n" +
                "                \"unhandled\": 7,\n" +
                "                \"handled\": 8\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 9,\n" +
                "                \"total\": 16,\n" +
                "                \"unhandled\": 6,\n" +
                "                \"handled\": 10\n" +
                "            },\n" +
                "            {\n" +
                "                \"date\": \"2024-04-26\",\n" +
                "                \"hour\": 10,\n" +
                "                \"total\": 0,\n" +
                "                \"unhandled\": 0,\n" +
                "                \"handled\": 0\n" +
                "            }\n" +
                "        ],\n" +
                "        \"ArmedMonitor\": {\n" +
                "            \"totalMonitorCount\": 16,\n" +
                "            \"onlineMonitorCount\": 16\n" +
                "        },\n" +
                "        \"AlarmCount\": {\n" +
                "            \"totalCount\": 0,\n" +
                "            \"isHandel\": 0\n" +
                "        }\n" +
                "    }\n" +
                "}";
        return str;
    }

    @Override
    public Map<String, Object> selectUWBIndexInfo(TEfAlarmVO tEfAlarmVO) {
        HashMap<String, Object> resultMap = new HashMap<>();
        TEfAlarm tEfAlarm =  tEfAlarmVO;
        LocalDate now = LocalDate.now();
        // 结合LocalDate和LocalTime的静态方法of来获取今天的零点时刻
        LocalDateTime startOfDay = LocalDateTime.of(now, LocalTime.MIDNIGHT);
        tEfAlarm.setStartTime(startOfDay);
        //如何将    tEfAlarmVO 内容强制转化为 TEfAlarm 赋值新的       TEfAlarm  tEfAlarm
        //获取当日报警信息记录
        List<TEfAlarm> tEfAlarmsList = tEfAlarmMapper.selectTEfAlarmList(tEfAlarm);
        //按照 tEfAlarmsList monitorDeviceType 分类统计不同的个数
        Map<String, Long> deviceTypeCount = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(TEfAlarm::getMonitorDeviceType, Collectors.counting()));
//        deviceTypeCount.forEach((deviceType, count) -> System.out.println("Device Type: " + deviceType + ", Count: " + count));
        //按照 tEfAlarmsList alarmArea 分类统计不同monitorDeviceType的个数
        //使用Java 8 Stream API进行统计
        Map<String, Map<String, Long>> areaToDeviceTypeCount = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(
                        TEfAlarm::getAlarmArea, //根据alarmArea分组
                        Collectors.groupingBy(TEfAlarm::getMonitorDeviceType, Collectors.counting()) //统计每个monitorDeviceType的数量
                ));


        TEfEquipmentDevice tEfEquipmentDevice = new TEfEquipmentDevice();
        List<TEfEquipmentDeviceVo> tEfEquipmentDeviceVos = tEfEquipmentDeviceMapper.selectTEfEquipmentDeviceDetailsList(tEfEquipmentDevice);
        // 统计每个设备的报警次数
        Map<String, Long> alarmDeviceCount = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(TEfAlarm::getAlarmDevice, Collectors.counting()));

        // 获取所有设备名称
        List<String> allEquipmentNames = tEfEquipmentDeviceVos.stream()
                .map(TEfEquipmentDeviceVo::getEquipmentName)
                .collect(Collectors.toList());

        Map<String, Long> alarmTypeCount = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(TEfAlarm::getAlarmType, Collectors.counting()));
        // 创建一个 List 对象来存储所有的告警类型
        List<String> allAlarmTypes = new ArrayList<>();
        allAlarmTypes.add("预警");
        allAlarmTypes.add("停机");

        // 创建最终的结果列表
        List<Map<String, Object>> alarmEquipmentCountList = allEquipmentNames.stream()
                .map(deviceName -> {
                    Map<String, Object> deviceInfo = new HashMap<>();
                    deviceInfo.put("equipmentName", deviceName);
                    deviceInfo.put("alarmCount", alarmDeviceCount.getOrDefault(deviceName, 0L));
                    return deviceInfo;
                })
                .sorted(Comparator.comparingLong(map -> (Long) map.get("alarmCount")))
                .collect(Collectors.toList());
        //反转数组 从大到小排序
        Collections.reverse(alarmEquipmentCountList);        // 创建最终的结果列表
        List<Map<String, Object>> alarmTypeCountList = allAlarmTypes.stream()
                .map(alarmType -> {
                    Map<String, Object> alarmTypeInfo = new HashMap<>();
                    alarmTypeInfo.put("alarmType", alarmType);
                    alarmTypeInfo.put("alarmCount", alarmTypeCount.getOrDefault(alarmType, 0L));
                    return alarmTypeInfo;
                })
                .collect(Collectors.toList());


        //我想重新构造 返回结构 首先获取所有的 AlarmDevice 名称 通过tEfEquipmentDeviceVos取出所有的 AlarmDevice 再遍历tEfAlarmsList 取出对应AlarmDevice 然后统计数量
        //使其最后的返回结果集为 list Map

        // 打印出结果示例
//        areaToDeviceTypeCount.forEach((area, deviceTypeCounts) -> {
//            System.out.println("Alarm Area: " + area);
//            deviceTypeCounts.forEach((deviceType, count) ->
//                    System.out.println("\tDevice Type: " + deviceType + ", Count: " + count));
//        });

        // 继续完善代码，将分类后的数据使用List<Map>存储
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> resultListAPP = new ArrayList<>();



        // 再完善一下，将第一次分类后的alarmArea的告警数量也加入最终的结果中
        Map<String, Long> areaAlarmCount = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(TEfAlarm::getAlarmArea, Collectors.counting()));

//        resultList.forEach(map -> map.put("AlarmCount", areaAlarmCount.get(map.get("AlarmArea"))));


        Set<String> allDeviceTypes = new HashSet<>();
        Set<String> allDeviceTypeCode = new HashSet<>();

        allDeviceTypes.add("AI识别");
        allDeviceTypes.add("热释电");
        allDeviceTypes.add("UWB");

        allDeviceTypeCode.add("1");
        allDeviceTypeCode.add("2");
        allDeviceTypeCode.add("3");


        // 先创建一个函数，用于初始化每个区域的设备类型计数映射
        Function<String, Map<String, Long>> initializeCounts = area -> {
            Map<String, Long> initialCounts = new HashMap<>();
            allDeviceTypes.forEach(deviceType -> initialCounts.put(deviceType, 0L));
            return initialCounts;
        };

        Map<String, Map<String, Long>> alarmCountByDeviceType = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(
                        TEfAlarm::getAlarmArea, // 根据alarmArea分组
                        Collectors.collectingAndThen( // 使用collectingAndThen来先初始化映射，然后再合并统计结果
                                Collectors.groupingBy(TEfAlarm::getMonitorDeviceType, Collectors.counting()),
                                counts -> { // 合并统计结果与预设的映射
                                    Map<String, Long> result = initializeCounts.apply(counts.keySet().iterator().next()); // 使用任意一个区域键来初始化映射
                                    counts.forEach((deviceType, count) -> result.merge(deviceType, count, Long::sum)); // 显式合并逻辑
                                    return result;
                                }
                        )
                ));

        List<TEfFenceArea> tEfFenceAreas = tEfFenceAreaMapper.selectTEfFenceAreaList(new TEfFenceArea());

        // 遍历每个围栏区域
        for (TEfFenceArea fenceArea : tEfFenceAreas) {
            String areaName = fenceArea.getAreaName();
            Map<String, Integer> deviceTypeCounts = new HashMap<>();
            Map<String, Integer> deviceTypeCodeCounts = new HashMap<>();

            deviceTypeCounts.put("UWB", 0); // 初始设备类型统计，可以根据实际需要添加其他类型
            deviceTypeCounts.put("AI识别", 0);
            deviceTypeCounts.put("热释电", 0);

            deviceTypeCodeCounts.put("1", 0); // 初始设备类型统计，可以根据实际需要添加其他类型
            deviceTypeCodeCounts.put("2", 0);
            deviceTypeCodeCounts.put("3", 0);


            int alarmCount = 0;
            int alarmCodeCount = 0;


            // 统计该区域下每种设备类型的告警数量
            for (TEfAlarm alarm : tEfAlarmsList) {
                if (areaName.equals(alarm.getAlarmArea())) {
                    String deviceType = alarm.getMonitorDeviceType();
                    if (deviceTypeCounts.containsKey(deviceType)) {
                        Integer integer = deviceTypeCounts.get(deviceType);
                        deviceTypeCounts.put(deviceType, deviceTypeCounts.get(deviceType) + 1);
                        if (deviceType.equals("UWB")){
                            deviceTypeCodeCounts.put("1", deviceTypeCounts.get(deviceType));
                        }
                        if (deviceType.equals("AI识别")){
                            deviceTypeCodeCounts.put("2", deviceTypeCounts.get(deviceType));
                        }
                        if (deviceType.equals("热释电")){
                            deviceTypeCodeCounts.put("3", deviceTypeCounts.get(deviceType) );
                        }
                        alarmCount++;
                    }
                }
            }

            // 构造结果对象
            Map<String, Object> resultItem = new HashMap<>();
            resultItem.put("DeviceTypeCounts", deviceTypeCounts);
            resultItem.put("DeviceTypeCodeCounts", deviceTypeCodeCounts);
            resultItem.put("AlarmArea", areaName);
            resultItem.put("AlarmCount", alarmCount);

            // 添加到结果列表
            resultList.add(resultItem);
        }
        Map<String, Long> aggregatedCounts = new HashMap<>();
        Map<String, Long> aggregatedCountCode = new HashMap<>();


        // 初始化设备类型
        String[] deviceTypes = {"UWB", "AI识别", "热释电"};

        String[] deviceCodeTypes = {"1", "2", "3"};


        // 遍历设备类型，初始化计数器
        for (String deviceType : deviceTypes) {
            aggregatedCounts.put(deviceType, 0L);
        }

        for (String deviceCodeType : deviceCodeTypes) {
            aggregatedCountCode.put(deviceCodeType, 0L);
        }

        // 遍历resultList中的每个Map
        for (Map<String, Object> result : resultList) {
            // 强制类型转换并获取DeviceTypeCounts
            @SuppressWarnings("unchecked")
            Map<String, Integer> deviceTypeCounts = (Map<String, Integer>) result.get("DeviceTypeCounts");

            // 遍历设备类型，累加计数
            for (String deviceType : deviceTypes) {
                Integer count = deviceTypeCounts.get(deviceType);
                if (count != null) {
                    aggregatedCounts.put(deviceType, aggregatedCounts.get(deviceType) + count);
                }
            }
        }
        // 遍历resultList中的每个Map
        for (Map<String, Object> result : resultList) {
            // 强制类型转换并获取DeviceTypeCounts
            @SuppressWarnings("unchecked")
            Map<String, Integer> deviceTypeCounts = (Map<String, Integer>) result.get("DeviceTypeCodeCounts");

            // 遍历设备类型，累加计数
            for (String deviceType : deviceCodeTypes) {
                Integer count = deviceTypeCounts.get(deviceType);
                if (count != null) {
                    aggregatedCountCode.put(deviceType, aggregatedCountCode.get(deviceType) + count);
                }
            }
        }


        sortResultListByAlarmCountDescending(resultList);
        // 将最终结果放入result中
        resultMap.put("resultList", resultList);
//        resultMap.put("resultListAPP", resultListAPP);
        resultMap.put("deviceTypeCount", aggregatedCounts);
        resultMap.put("deviceTypeCodeCount", aggregatedCountCode);
//        resultMap.put("alarmCountByDeviceType", aggregatedCountCode);
        resultMap.put("alarmEquipmentCountList", alarmEquipmentCountList);
        resultMap.put("alarmTypeCountList", alarmTypeCountList);



        return  resultMap;
    }
    public static void sortResultListByAlarmCountDescending(List<Map<String, Object>> resultList) {
        resultList.sort((o1, o2) -> {
            Integer alarmCount1 = ((Number) o1.get("AlarmCount")).intValue();
            Integer alarmCount2 = ((Number) o2.get("AlarmCount")).intValue();
            return alarmCount2.compareTo(alarmCount1);
        });
    }

    @Override
    public Map<String, Object> selectUWBIndexInfo2(TEfAlarmVO tEfAlarmVO) {
        HashMap<String, Object> resultMap = new HashMap<>();
        TEfAlarm tEfAlarm =  tEfAlarmVO;

        LocalDate now = LocalDate.now();
        // 结合LocalDate和LocalTime的静态方法of来获取今天的零点时刻
        LocalDateTime startOfDay = LocalDateTime.of(now, LocalTime.MIDNIGHT);
        tEfAlarm.setStartTime(startOfDay);
        List<TEfAlarm> tEfAlarmsList = tEfAlarmMapper.selectTEfAlarmList(tEfAlarm);
        // 将最终结果放入result中
        // 假设allDeviceTypes是包含了所有你关心的设备类型的集合
        Set<String> allDeviceTypes = new HashSet<>();
        allDeviceTypes.add("AI识别");
        allDeviceTypes.add("热释电");
        allDeviceTypes.add("UWB");

        Set<String> allDeviceTypesCode = new HashSet<>();
        allDeviceTypes.add("1");
        allDeviceTypes.add("2");
        allDeviceTypes.add("3");


        // 先创建一个函数，用于初始化每个区域的设备类型计数映射
        Function<String, Map<String, Long>> initializeCounts = area -> {
            Map<String, Long> initialCounts = new HashMap<>();
            allDeviceTypes.forEach(deviceType -> initialCounts.put(deviceType, 0L));
            return initialCounts;
        };

        Map<String, Map<String, Long>> areaToDeviceTypeCount = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(
                        TEfAlarm::getAlarmArea, // 根据alarmArea分组
                        Collectors.collectingAndThen( // 使用collectingAndThen来先初始化映射，然后再合并统计结果
                                Collectors.groupingBy(TEfAlarm::getMonitorDeviceType, Collectors.counting()),
                                counts -> { // 合并统计结果与预设的映射
                                    Map<String, Long> result = initializeCounts.apply(counts.keySet().iterator().next()); // 使用任意一个区域键来初始化映射
                                    counts.forEach((deviceType, count) -> result.merge(deviceType, count, Long::sum)); // 显式合并逻辑
                                    return result;
                                }
                        )
                ));


        List<Map.Entry<String, Map<String, Long>>> areaToDeviceTypeCountList = tEfAlarmsList.stream()
                .collect(Collectors.groupingBy(
                        TEfAlarm::getAlarmArea,
                        Collectors.collectingAndThen(
                                Collectors.groupingBy(TEfAlarm::getMonitorDeviceType, Collectors.counting()),
                                counts -> {
                                    Map<String, Long> result = initializeCounts.apply(counts.keySet().iterator().next());
                                    counts.forEach((deviceType, count) -> result.merge(deviceType, count, Long::sum));
                                    return result;
                                }
                        )
                ))
                .entrySet().stream() // 转换为Map.Entry的Stream
                .collect(Collectors.toList()); // 收集到List<Map.Entry<String, Map<String, Long>>>

        // 确保每个区域的映射中包含了所有指定设备类型，即使数量为0
        areaToDeviceTypeCount.values().forEach(map -> {
            allDeviceTypes.forEach(deviceType -> map.putIfAbsent(deviceType, 0L));
        });
        // 将Map<String, Map<String, Long>>转换为List<Map<String, Long>>
        List<Map<String, Long>> resultTypeCountList = new ArrayList<>(areaToDeviceTypeCount.values());
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<Map<String, Object>> resultListApp = new ArrayList<>();


        for (Map.Entry<String, Map<String, Long>> areaEntry : areaToDeviceTypeCountList) {
            HashMap<String, Object> map = new HashMap<>();
            HashMap<String, Object> mapCode = new HashMap<>();

            HashMap<String, Object> TypeMap = new HashMap<>();
            HashMap<String, Object> TypeMapCode = new HashMap<>();

            String key = areaEntry.getKey();
            Long countSum=0L;

            Map<String, Long> value = areaEntry.getValue();
            countSum=value.get("UWB")+value.get("AI识别")+value.get("热释电");
            TypeMap.put("UWB",value.get("UWB"));
            TypeMap.put("AI识别",value.get("AI识别"));
            TypeMap.put("热释电",value.get("热释电"));

            TypeMapCode.put("1",value.get("UWB"));
            TypeMapCode.put("2",value.get("AI识别"));
            TypeMapCode.put("3",value.get("热释电"));
            map.put("AlarmArea",key);
            map.put("DeviceTypeCounts",TypeMap);
            map.put("AlarmCount",countSum);
            mapCode.put("AlarmArea",key);
            mapCode.put("DeviceTypeCounts",TypeMapCode);
            mapCode.put("AlarmCount",countSum);
            resultList.add(map);
            resultListApp.add(mapCode);

        }


        resultMap.put("resultListApp",resultListApp);
        resultMap.put("resultList",resultList);
        resultMap.put("resultTypeCountList",resultTypeCountList);
        resultMap.put("areaToDeviceTypeCountList",areaToDeviceTypeCountList);
        resultMap.put("areaToDeviceTypeCount",areaToDeviceTypeCount);

        return  resultMap;
    }

    @Override
    public Map<String, Object> selectUWBIndexInfo3(TEfAlarmVO tEfAlarmVO) {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        TEfAlarm tEfAlarm =  tEfAlarmVO;
//        TEfFenceArea tEfFenceArea = new TEfFenceArea();
        LocalDate now = LocalDate.now();
        // 结合LocalDate和LocalTime的静态方法of来获取今天的零点时刻
        LocalDateTime startOfDay = LocalDateTime.of(now, LocalTime.MIDNIGHT);
        tEfAlarm.setStartTime(startOfDay);
        List<TEfAlarm> tEfAlarmsList = tEfAlarmMapper.selectTEfAlarmList(tEfAlarm);
        List<TEfFenceArea> tEfFenceAreas = tEfFenceAreaMapper.selectTEfFenceAreaList(new TEfFenceArea());

        // 遍历每个围栏区域
        for (TEfFenceArea fenceArea : tEfFenceAreas) {
            String areaName = fenceArea.getAreaName();
            Map<String, Integer> deviceTypeCounts = new HashMap<>();
            deviceTypeCounts.put("UWB", 0); // 初始设备类型统计，可以根据实际需要添加其他类型
            deviceTypeCounts.put("AI识别", 0);
            deviceTypeCounts.put("热释电", 0);

            int alarmCount = 0;

            // 统计该区域下每种设备类型的告警数量
            for (TEfAlarm alarm : tEfAlarmsList) {
                if (areaName.equals(alarm.getAlarmArea())) {
                    String deviceType = alarm.getMonitorDeviceType();
                    if (deviceTypeCounts.containsKey(deviceType)) {
                        deviceTypeCounts.put(deviceType, deviceTypeCounts.get(deviceType) + 1);
                        alarmCount++;
                    }
                }
            }

            // 构造结果对象
            Map<String, Object> resultItem = new HashMap<>();
            resultItem.put("DeviceTypeCounts", deviceTypeCounts);
            resultItem.put("AlarmArea", areaName);
            resultItem.put("AlarmCount", alarmCount);

            // 添加到结果列表
            resultList.add(resultItem);
        }

        for (TEfFenceArea  area:tEfFenceAreas){
            String areaName = area.getAreaName();

        }

        resultMap.put("resultList",resultList);




        return  resultMap;
    }


    @Override
    public Map<String, Object> selectAlarmCountByDate(TEfAlarm tEfAlarm ) {
        HashMap<String, Object> result = new HashMap<>();

        // tEfAlarmsList 按照 alarmTime 对数据进行三次分类
        //1.按照前日期 分小时段统计各个报警的次数
        //2.按照前日期 分日期段统计各个报警的次数  近7天 近30天
        //3.按照当前年份 分月份统计各个报警次数
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay(); // 当天的00:00:00
        LocalDateTime now = LocalDateTime.now(); // 当前时刻
        tEfAlarm.setStartTime(today.minusDays(100).atStartOfDay());
        List<TEfAlarm> tEfAlarmsList = tEfAlarmMapper.selectTEfAlarmList(tEfAlarm);
        // 生成从今天0点到当前时刻的所有小时
        List<LocalDateTime> hoursOfToday = IntStream.rangeClosed(0, now.getHour())
                .mapToObj(hour -> startOfDay.plusHours(hour))
                .collect(Collectors.toList());

        // 统计每个小时的报警次数，注意这里需要将时间点转换为LocalDateTime以精确匹配
        Map<LocalDateTime, Long> hourlyCounts = tEfAlarmsList.stream()
                .filter(alarm -> alarm.getAlarmTime().toLocalDate().equals(today))
                .map(alarm -> alarm.getAlarmTime())
                .collect(Collectors.groupingBy(
                        Function.identity(), // 直接使用LocalDateTime作为key
                        TreeMap::new, // 保持小时排序
                        Collectors.counting()));

        // 构造返回的结果列表
        List<Map<String, Object>> hourStatisticsCount = hoursOfToday.stream()
                .map(hour -> {
                    // 统计每个小时内 alarmType 为 0 和 1 的报警数
                    long countType0 = tEfAlarmsList.stream()
                            .filter(alarm ->  alarm.getAlarmTime().isAfter(hour) && alarm.getAlarmTime().isBefore(hour.plusHours(1))
                            && alarm.getAlarmType().equals("预警"))
                            .count();
                    long countType1 = tEfAlarmsList.stream()
                            .filter(alarm ->  alarm.getAlarmTime().isAfter(hour) && alarm.getAlarmTime().isBefore(hour.plusHours(1))
                                    && alarm.getAlarmType().equals("停机"))
                            .count();
                    long totalCount = countType0 + countType1;

                    // 构造每小时的统计信息
                    // 构造每小时的统计信息
                    Map<String, Object> hourStatistics = new HashMap<>();
                    hourStatistics.put("hour", hour.getHour());
                    hourStatistics.put("alarmType0", countType0);
                    hourStatistics.put("alarmType1", countType1);
                    hourStatistics.put("alarmCount", totalCount);
                    return hourStatistics;
                })
                .collect(Collectors.toList());

        //当日报警
        result.put("hourStatisticsCount",hourStatisticsCount);

        // 获取近7天和近30天的日期范围
        LocalDate startOfWeek = getDaysAgo(7);
        LocalDate startOfMonth = getDaysAgo(30);
        // 创建一个方法来生成日期范围内的每一天
        List<LocalDate> daysInRange7 = generateDates(startOfWeek, today.plusDays(1));
        List<Map<String, Object>> dayStatisticsCount7 =new ArrayList<>();
        for(LocalDate day: daysInRange7 ){
            Map<String, Object> dayStatistics = new HashMap<>();
            long countType0 = 0L;
            long countType1 = 0L;

            for (TEfAlarm alarm :tEfAlarmsList){

               if (alarm.getAlarmTime().toLocalDate().equals(day)){
                   if (alarm.getAlarmType().equals("预警")){
                       countType0++;
                   }
                   if (alarm.getAlarmType().equals("停机")){
                       countType1++;
                   }
               }
            }
            long totalCount = countType0 + countType1;
            dayStatistics.put("date", day);
            dayStatistics.put("alarmType0", countType0);
            dayStatistics.put("alarmType1", countType1);
            dayStatistics.put("alarmCount", totalCount);
            dayStatisticsCount7.add(dayStatistics);
        }
        result.put("sevenDayStatisticsCount",dayStatisticsCount7);
        List<LocalDate> daysInRange30 = generateDates(startOfMonth, today.plusDays(1));
        List<Map<String, Object>> dayStatisticsCount30 =new ArrayList<>();
        for(LocalDate day: daysInRange30 ){
            Map<String, Object> dayStatistics = new HashMap<>();
            long countType0 = 0L;
            long countType1 = 0L;

            for (TEfAlarm alarm :tEfAlarmsList){

                if (alarm.getAlarmTime().toLocalDate().equals(day)){
                    if (alarm.getAlarmType().equals("预警")){
                        countType0++;
                    }
                    if (alarm.getAlarmType().equals("停机")){
                        countType1++;
                    }
                }
            }
            long totalCount = countType0 + countType1;
            dayStatistics.put("date", day);
            dayStatistics.put("alarmType0", countType0);
            dayStatistics.put("alarmType1", countType1);
            dayStatistics.put("alarmCount", totalCount);
            dayStatisticsCount30.add(dayStatistics);
        }
        result.put("thirtyDayStatisticsCount",dayStatisticsCount30);

        return result;
    }

    private static LocalDate getDaysAgo(int daysAgo) {
        return LocalDate.now().minusDays(daysAgo-1);
    }

    private static List<LocalDate> generateDates(LocalDate startDate, LocalDate endDate) {
        return IntStream.iterate((int)startDate.toEpochDay(), n -> n + 1)
                .limit((int)(endDate.toEpochDay() - startDate.toEpochDay()))
                .mapToObj(LocalDate::ofEpochDay)
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> selectDeviceCountByType(TDeviceStatus tDeviceStatus) {
        HashMap<String, Object> resultMap = new HashMap<>();

        List<TDeviceStatus> tDeviceStatuses = tDeviceStatusMapper.selectTDeviceStatusList(tDeviceStatus);

        // 假设 "启用" 状态的值为 "Enabled"
        final String ENABLED_STATUS = "启用";

        // 创建一个Map来存储每个设备类型及其对应的统计信息
        Map<String, Map<String, Long>> combinedStats = new HashMap<>();

        // 首先按设备类型分组并统计总数
        Map<String, Long> typeTotalCount = tDeviceStatuses.stream()
                .collect(Collectors.groupingBy(TDeviceStatus::getDeviceType, Collectors.counting()));

        // 然后在每个类型中统计启用状态的设备数量
        Map<String, Long> enabledCountByType = tDeviceStatuses.stream()
                .filter(deviceStatus -> ENABLED_STATUS.equals(deviceStatus.getDeviceStatus()))
                .collect(Collectors.groupingBy(TDeviceStatus::getDeviceType, Collectors.counting()));

        // 合并统计结果到combinedStats
        typeTotalCount.forEach((type, totalCount) -> {
            Map<String, Long> statsForType = new HashMap<>();
            statsForType.put("totalCount", totalCount);
            statsForType.put("enableCount", enabledCountByType.getOrDefault(type, 0L));
            combinedStats.put(type, statsForType);
        });

        // 如果需要，可以将combinedStats添加到resultMap中
        resultMap.put("deviceTypeStats", combinedStats);
        return resultMap;
    }

    @Override
    public Map<String, Object> selectAlarmCountByAlarmType(TDeviceStatus tDeviceStatus) {
        return null;
    }


    @Override
    public Map<String, Object> selectDeviceCountAndAlarmCount(TDeviceStatus tDeviceStatus) {
        HashMap<String, Object> resultMap = new HashMap<>();

        // 获取所有设备状态
        List<TDeviceStatus> allDeviceStatuses = tDeviceStatusMapper.selectTDeviceStatusList(new TDeviceStatus());
        // 统计正常在线的设备数量
        long onlineDeviceCount= allDeviceStatuses.stream()
                .filter(device -> "在线".equals(device.getDeviceStatus()))
                .count();

        // 获取设备状态列表
        TEfEquipmentDevice equipmentDevice = new TEfEquipmentDevice();
        List<TEfEquipmentDeviceVo> equipmentDevices = tEfEquipmentDeviceService.getEquipmentStatusV3(equipmentDevice) ;


        // 统计正常在线的设备数量
        long onlineEquipmentCount = equipmentDevices.stream()
                .filter(device -> "正常".equals(device.getEquipmentStatus()))
                .count();

        // 填充结果映射
        resultMap.put("DeviceCount", allDeviceStatuses.size());
        resultMap.put("DeviceIsOnlineCount", onlineDeviceCount);

        resultMap.put("equipmentDeviceTotal", equipmentDevices.size());
        resultMap.put("equipmentDeviceIsOnlineTotal", onlineEquipmentCount);


        // 获取今天的日期并设置查询开始时间为零点
        LocalDateTime todayZeroTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);

        // 获取当天的报警信息
        TEfAlarm alarmQuery = new TEfAlarm();
        alarmQuery.setStartTime(todayZeroTime);
        List<TEfAlarm> alarmsToday = tEfAlarmMapper.selectTEfAlarmList(alarmQuery);

        resultMap.put("AlarmCount", alarmsToday.size());

        return resultMap;
    }
//
}
